package com.smart.primary.util;



import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;


public class ImgUtil {	
	/**
	 * @Description: 将base64编码字符串转换为图片
	 * @Author: 
	 * @CreateTime: 
	 * @param imgStr base64编码字符串
	 * @param path 图片路径-具体到文件
	 * @return
	*/
	public static Boolean decode(String imgStr, String path) {
		if(StringUtils.isBlank(imgStr) || StringUtils.isBlank(path)) {
			return false;
		}else {
			BASE64Decoder decoder = new BASE64Decoder();			
			try {
				byte[] b = decoder.decodeBuffer(imgStr);
				// 处理数据
				for (int i = 0; i < b.length; i++) {
					if(b[i] < 0) {
						b[i] += 256;
					}
				}
				OutputStream out = new FileOutputStream(path);
				out.write(b);
				out.flush();
				out.close();
				return true;
			} catch (IOException e) {				
				e.printStackTrace();
				return false;
			}
		}		
	}

	/**
	 * @Description: 根据图片地址转换为base64编码字符串
	 * @Author: 
	 * @CreateTime: 
	 * @return
	 */
	public static String encode(String imgFile) {
	    InputStream inputStream = null;
	    byte[] data = null;
	    try {
	        inputStream = new FileInputStream(imgFile);
	        data = new byte[inputStream.available()];
	        inputStream.read(data);
	        inputStream.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    // 加密
	    BASE64Encoder encoder = new BASE64Encoder();
	    return encoder.encode(data);
	}
	  /**
	   * 图片改变格式并压缩大小
	   * @param forPath 图片原始地址
	   * @param toPath	压缩地址
	   */
	   public static void yaSuoImg(String forPath,String toPath) {
		   try {
			     //改变格式
			//	 Thumbnails.of(forPath).scale(1f).toFile(toPath);
				 //第一次压缩
				 Thumbnails.of(toPath).width(414).toFile(toPath);
				 //大的话一直压缩
//				 File srcFileJPG = new File(toPath);
//				 while(true) {
//					 if(srcFileJPG.length()>102400*3) {
//							Thumbnails.of(toPath).scale(0.9f).toFile(toPath);
//						}else {
//							break;
//						}
//				 }
			} catch (IOException e) {
				e.printStackTrace();
			}
	   }


	   /**
	     * 图片水印
	     * 
	     * @throws IOException
	     */
	    public static void test5() throws IOException {
	        /**
	         * watermark(位置，水印图，透明度)
	         */
	        Thumbnails.of("C:\\Users\\Administrator\\Desktop/22.jpg").size(1280, 1024).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("C:\\Users\\Administrator\\Desktop/11.jpg")), 0.5f)
	                .outputQuality(0.8f).toFile("C:\\Users\\Administrator\\Desktop/33.jpg");
	    }
	public static void pressImg(String imgPath,String pressPath,String imgToPath){
		try {

			Thumbnails.of(imgPath)
					.size(1280, 1024)
					.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(pressPath)), 0.5f)
					.outputQuality(0.8f).toFile(imgToPath);
		}catch (Exception e){
			e.getMessage();
		}
	}

	     /**  
	     * 添加文字水印  
	     * @param targetImg 目标图片路径，如：C://myPictrue//1.jpg  
	     * @param pressText 水印文字， 如：中国证券网  
	     * @param fontName 字体名称，    如：宋体  
	     * @param fontStyle 字体样式，如：粗体和斜体(Font.BOLD|Font.ITALIC)  
	     * @param fontSize 字体大小，单位为像素  
	     * @param color 字体颜色  
	     * @param x 水印文字距离目标图片左侧的偏移量，如果x<0, 则在正中间  
	     * @param y 水印文字距离目标图片上侧的偏移量，如果y<0, 则在正中间  
	     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)  
	     */  
	    public static void pressText(String targetImg,String pressText,String fontName,int fontStyle,int fontSize,Color color,int x,int y,float alpha){  
	        try {  
	            File file = new File(targetImg);  
	            Image image = ImageIO.read(file);  
	            int width = image.getWidth(null);  
	            int height = image.getHeight(null);  
	              
	            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
	            Graphics2D g = bufferedImage.createGraphics();  
	            g.drawImage(image,0,0, width, height, null);  
	            g.setFont(new Font(fontName, fontStyle, fontSize));  
	            g.setColor(color);  
	            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));  
	              
	            int width_wi = fontSize*getTextLength(pressText);  
	            int height_wi = fontSize;  
	              
	            int widthDiff = width-width_wi;  
	            int heightDiff = height-height_wi;  
	            if(x<0){  
	                x = widthDiff/2;  
	            }else if(x>widthDiff){  
	                x=widthDiff;  
	            }  
	              
	            if(y<0){  
	                y = heightDiff/2;  
	            }else if(y>heightDiff){  
	                y = heightDiff;  
	            }  
	            g.drawString(pressText, x, y+height_wi);//水印文件  
	            g.dispose();  
	            ImageIO.write(bufferedImage, "JPEG", file);  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	    /** 
	     * 计算文字像素长度 
	     * @param text 
	     * @return 
	     */  
	    private static int getTextLength(String text){  
	        int textLength = text.length();  
	        int length = textLength;  
	        for (int i = 0; i < textLength; i++) {  
	            int wordLength = String.valueOf(text.charAt(i)).getBytes().length;  
	            if(wordLength > 1){  
	                length+=(wordLength-1);  
	            }  
	        }  
	          
	        return length%2==0 ? length/2:length/2+1;  
	    }

//	/**
//	 *  生成二维码图片
//	 *  带底图
//	 * @param str
//	 * @param imagePath
//	 * @param newfileName
//	 * @return
//	 * @throws FileNotFoundException
//	 */
//	public static String getTwoCodeImage(String str,String imagePath,String newfileName){
//		try {
//			// 获取二维码图片
//			byte[] bytes = null;
//			BufferedImage encode = RQCodeUtils.encode(str);
//
//			File file = new File(imagePath);
//			InputStream stream=new FileInputStream(file);
//			BufferedImage image = ImageIO.read(stream);
//			Graphics2D g = image.createGraphics();
//			g.drawImage(encode,263,1001,230,230,null);
//			g.dispose();
//			File outputfile = new File(newfileName);
//			ImageIO.write(image, "jpg", outputfile);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return "";
//	}


//	public static void getTwoCodeImage(String str,String imagePath){
//		int width=300;
//		int height=300;
//		String format="jpg";
//		try {
//			BitMatrix bm = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, width, height);
//			Path file=new File(imagePath).toPath();
//			MatrixToImageWriter.writeToPath(bm, format, file);
//		} catch (WriterException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

	public static String getTwoCodeText(String filePath) {
		try {
			MultiFormatReader reader=new MultiFormatReader();//需要详细了解MultiFormatReader的小伙伴可以点我一下官方去看文档
			File f=new File(filePath);
			BufferedImage image=ImageIO.read(f);
			BinaryBitmap bb=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
			HashMap map =new HashMap();
			map.put(EncodeHintType.CHARACTER_SET, "utf-8");
			Result result = reader.decode(bb,map);
			return result.getText();
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}


	public static void main(String[] args) {
		String forPath="C:\\Users\\yuezhan\\Desktop\\q.png";
		String toPath="C:\\Users\\yuezhan\\Desktop\\a.png";
		yaSuoImg(forPath,toPath);
//		System.out.println(encode(toPath));;
//		for (int i=1;i<4;i++){
//			String forPath="C:\\Users\\li\\Desktop\\11\\"+i+".png";
//			String toPath="C:\\Users\\li\\Desktop\\11\\1"+i+".png";
//
//			yaSuoImg(forPath,toPath);
//		}
		//getTwoCodeImage("http://api.facetuis.com/facetuis/1.0/user/enroll/77666",forPath,toPath);

		//加文字水印
//		pressText("C:\\Users\\mayn\\Desktop\\new2.jpg", "江波之印", "宋体", Font.BOLD, 20, Color.WHITE,10, 10, 1f);
////
////		String str=encode("C:\\Users\\mayn\\Desktop\\new2.jpg");
////		System.out.println(str);
////		decode(str,"C:\\Users\\mayn\\Desktop\\new22.jpg");
	}
}
